package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.pojo.AddressBook;
import com.itheima.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    //新增地址
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook){
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookService.save(addressBook);
        return R.success(addressBook);
    }

    //设置默认地址
    @PutMapping("/default")
    public R<AddressBook> setdefault(@RequestBody AddressBook addressBook){


        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());

        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }

    //根据id查询
    @GetMapping("/{id}")
    public R<AddressBook> getaddress(@PathVariable Long id){
        AddressBook byId = addressBookService.getById(id);
        if (byId!=null){
            return R.success(byId);
        }
        return R.error("id不存在");
    }

    //查询默认地址
    @GetMapping("/default")
    public R<AddressBook> gatdefault(){
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getIsDefault,1);
        wrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        AddressBook one = addressBookService.getOne(wrapper);
        if (one!=null){
            return R.success(one);
        }
        return R.error("查询不到默认！");
    }


    //查询 查询指定用户的全部地址
    @GetMapping("/list")
    public R<List<AddressBook>> getlist(AddressBook addressBook){

        addressBook.setUserId(BaseContext.getCurrentId());

        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null != addressBook.getUserId(),AddressBook::getUserId,addressBook.getUserId());
        wrapper.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> list = addressBookService.list(wrapper);
        return R.success(list);
    }

    //删除
    @DeleteMapping
    public  R<String> deleteaddress(@RequestParam List<Long> ids){
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(AddressBook::getId,ids);
        addressBookService.remove(wrapper);
        return R.success("删除成功！");
    }

    //修改
    @PutMapping
    public R<String> updateaddress(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return R.success("修改成功！");
    }

}
